package org.example.ymcc.web.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.ymcc.constant.Constants;
import org.example.ymcc.constant.RConst;
import org.example.ymcc.ro.PayRo;
import org.example.ymcc.service.IPayOrderService;
import org.example.ymcc.domain.PayOrder;
import org.example.ymcc.query.PayOrderQuery;
import org.example.ymcc.result.JsonResult;
import org.example.ymcc.result.PageList;
import org.example.ymcc.util.AliPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/payOrder")
public class PayOrderController {
    @Autowired
    public AliPayUtil aliPayUtil;
    @Autowired
    public IPayOrderService payOrderService;

    /**
     *  由支付宝来主动调用我们接口
     *  安全问题  防止篡改
     * @param request
     * @return
     */
    @PostMapping("/callback")
    public String callback(HttpServletRequest request) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,String> newMp = new HashMap<>(parameterMap.size());
        parameterMap.forEach((key,value)-> newMp.put(key,value==null?"":value[0]));
        //二次验签的请求
        Boolean bl = Factory.Payment.Common().verifyNotify(newMp);//发送请求
        if(bl){
            if(Constants.TRADE_SUCCESS.equals(newMp.get("trade_status"))){
                //支付单状态修改   记录支付流水
                //订单状态修改
                //保存用户购买记录
                payOrderService.paySuccess(newMp);
            }else {
                return "error";
            }
        }else {
            //记录日志
            //发送管理员
        }
        return "success";
    }

    @GetMapping("/checkPayOrder/{orderNo}")
    public JsonResult checkPayOrder(@PathVariable("orderNo")String orderNo){
        PayOrder one = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderNo));
        if(one != null){
            return JsonResult.success();
        }
        return JsonResult.error("未查询改订单数据");
    }

    @PostMapping("/apply")
    public JsonResult apply(@RequestBody @Valid PayRo ro){
        PayOrder one = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, ro.getOrderNo()));
        if(one != null){
            //支付要做的事情
            String pay = aliPayUtil.toPay(one.getSubject(),ro.getOrderNo(),one.getAmount().toString(),ro.getCallUrl());
            return JsonResult.success().setData(pay);
        }
        return JsonResult.error("未查询改订单数据");
    }

    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody PayOrder payOrder){
        if(payOrder.getId()!=null){
            payOrderService.updateById(payOrder);
        }else{
            payOrderService.save(payOrder);
        }
        return JsonResult.success();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        payOrderService.removeById(id);
        return JsonResult.success();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.success().setData(payOrderService.getById(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.success().setData(payOrderService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody PayOrderQuery query){
        Page<PayOrder> page = new Page<PayOrder>(query.getPageNo(), query.getPageSize());
        page = payOrderService.page(page);
        return JsonResult.success().setData(new PageList<PayOrder>(page.getTotal(), page.getRecords()));
    }
}
